package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.UserInfoDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author LX
 * @since 2022-06-18
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * app端用户登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AppLoginDto dto) {
        Map<String,Object> result = new HashMap<>();
        int userId = 0;
//        判断是否手机号密码登录
        if(StringUtils.isNotBlank(dto.getPhone()) &&
                StringUtils.isNotBlank(dto.getPassword())){
//        通过手机号查询用户信息
            QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
//        如果没有用户信息，报错
            if(apUser==null){
                throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
//        验证密码
            boolean b = encoder.matches(dto.getPassword(), apUser.getPassword());
            if(!b){
//                密码不正确
                log.error("密码不正确");
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            result.put("user", BeanHelper.copyProperties(apUser, UserInfoDto.class));
            userId = apUser.getId();
        }else{
//        如果是设备登录，生成token
            if(StringUtils.isBlank(dto.getEquipmentId())){
                throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
//        生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userId, 600);
        result.put("token",token);
        return result;
    }
}
